package com.wangnian.wangcai.service.api;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.wangnian.wangcai.config.Config;
import com.wangnian.wangcai.dao.ChiGu;
import com.wangnian.wangcai.util.ChatbotSend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ThsService implements ApiService {

    @Value("${ths.http}")
    private String thsHttp;

    private static final Logger logger = LoggerFactory.getLogger(ThsService.class);

    /**
     * 同花顺卖
     *
     * @param code
     * @param count
     * @param remarks
     */
    @Override
    public synchronized void sell(String code, int count, String remarks) {
        try {
            HttpRequest httpRequest = HttpRequest.get(thsHttp + "2251181679wangniancmd?cmd=sell " + code + " dsj5 " + count + " -notip");
            httpRequest.timeout(1000);
            String strResult1 = httpRequest.execute().body();
            logger.info("卖出返回:{}", strResult1);
            JSONObject jsonObject1 = JSONObject.parseObject(strResult1);
            if (jsonObject1.getInteger("retCode") == -1) {
                Thread.sleep(1000);
                ChatbotSend.send("卖出请求成功:" + remarks);
            } else {
                ChatbotSend.send(jsonObject1.getString("msg"));
            }
        } catch (Exception e) {
            logger.error("", e);
            ChatbotSend.send("卖出异常:" + e.getMessage());
        } finally {
            Config.allowRefresh();
        }
    }


    /**
     * THS买
     *
     * @param code
     * @param count
     * @param stockName
     */
    @Override
    public synchronized boolean buy(String code, int count, double price, String stockName) {
        try {
            if (balance() < count * price) {
                return false;
            }
            HttpRequest httpRequest = HttpRequest.get(thsHttp + "2251181679wangniancmd?cmd=buy " + code + " dsj5 " + count + " -notip");
            httpRequest.timeout(1000);
            String strResult1 = httpRequest.execute().body();
            logger.info("买入返回:{}", strResult1);
            JSONObject jsonObject1 = JSONObject.parseObject(strResult1);
            if (jsonObject1.getInteger("retCode") == -1) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                ChatbotSend.send("买入请求失败:" + stockName + jsonObject1.toJSONString());
                return false;
            }
        } catch (Exception e) {
            ChatbotSend.send("买入异常:" + e.getMessage());
            return false;
        } finally {
            Config.allowRefresh();
        }
        return true;
    }


    public synchronized JSONObject thsMoney() {
        try {
            HttpRequest httpRequest = HttpRequest.get(thsHttp + "g_money");
            httpRequest.timeout(1000);
            String strResult = httpRequest.execute().body();
            logger.info("THS余额:{}", strResult);
            JSONObject jsonObject = JSONObject.parseObject(strResult);
            return jsonObject;
        } catch (Exception e) {
            logger.error("", e);
            ChatbotSend.send("THS查询余额异常:" + e.getMessage());
        }
        return null;
    }

    public static double balance = 0;

    /**
     * THS金额
     *
     * @return
     */
    @Override
    public Double balance() {
        try {
            if (balance == 0 || Config.refreshBalance) {
                balance = thsMoney().getDouble("kyje");
                Config.refreshBalance = false;
            }
        } catch (Exception ex) {
            logger.error("可用余额异常");
        }
        return balance;
    }

    @Override
    public Double positionProfit() {
        return null;
    }


    /**
     * 持仓情况
     *
     * @return
     */
    @Override
    public synchronized List<ChiGu> position(int aCount) {
        List<ChiGu> chiGuList = new ArrayList<>();
        try {
            HttpRequest httpRequest = HttpRequest.get(thsHttp + "g_position");
            httpRequest.timeout(1000);
            String strResult = httpRequest.execute().body();
            JSONObject jsonObject = JSONObject.parseObject(strResult);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                JSONObject chiguJSON = (JSONObject) entry.getValue();
                String stockNo = chiguJSON.getString("zqdm");
                Double sumMoney = chiguJSON.getDouble("sz");
                String stockName = chiguJSON.getString("zqmc");
                int availableCount = new BigDecimal(chiguJSON.getString("kyye")).intValue();
                int gpye = new BigDecimal(chiguJSON.getString("gpye")).intValue();
                double zfMoney = chiguJSON.getDouble("yk");
                Double cost = chiguJSON.getDouble("cbj");
                if (gpye >= aCount) {
                    ChiGu chiGu = new ChiGu();
                    chiGu.setCode(stockNo);
                    chiGu.setName(stockName);
                    chiGu.setCost(cost);
                    chiGu.setSumMoney(sumMoney);
                    chiGu.setYkMoney(zfMoney);
                    chiGu.setCount(availableCount);
                    chiGuList.add(chiGu);
                }
            }
        } catch (Exception ex) {
            ChatbotSend.send("查询同花顺持仓失败" + ex.getMessage());
            logger.info("", ex);
        }
        return chiGuList;
    }

    @Override
    public void autoRepayment() {

    }

    /**
     * 获取的数据
     *
     * @param codeList
     */
    public synchronized Map<String, Double> getThsData(Set<String> codeList) {
        Map<String, Double> hashMap = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (String code : codeList) {
            stringBuilder.append(code).append(",");
        }
        String codeStr = stringBuilder.toString();
        HttpRequest httpRequest = HttpRequest.get(thsHttp + "get_quote?list=" + codeStr);
        httpRequest.timeout(1000);
        String strResult = httpRequest.execute().body();
        JSONObject jsonObject = JSONObject.parseObject(strResult);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            JSONObject quoteJSON = (JSONObject) entry.getValue();
            double price = quoteJSON.getDouble("price");
            hashMap.put(entry.getKey(), price);
        }
        return hashMap;
    }
}
